<template>
  <div style="padding-top: 10px;background-color: #ffffff">
    <!-- 表单 -->
    <el-form :inline="true" :model="page" class="demo-form-inline">
      <el-form-item label="">
        <el-input v-model="page.queryString" placeholder="药名  /  别名 / 分类"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button  v-if="deleteButton" type="danger" @click="batchDeletion" icon="el-icon-delete">批量删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" @click="refreshTr">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" :pagination="false" border style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="50%" align="center" />
      <el-table-column prop="id" label="编号" width="200" align="center">
        <template v-slot="scpoe">
          <el-tag type="danger">
            <span>{{scpoe.row.id}}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="药名" width="180" align="center"></el-table-column>
      <el-table-column prop="image" label="图片" width="180" align="center">
        <template v-slot="{ row }">
          <img :src="row.imageUrl" width="100px" height="70px">
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" width="180" align="center"></el-table-column>
      <el-table-column prop="alias" label="别名" width="180" align="center"></el-table-column>
      <el-table-column prop="medicinalPart" label="药用部位" width="140" align="center"></el-table-column>
      <el-table-column prop="clinicalApplication" label="临床应用" width="1200" align="center"></el-table-column>
      <el-table-column prop="pharmacologicalResearch" label="药理研究" width="700" align="center"></el-table-column>
      <el-table-column prop="contraindications" label="使用禁忌" width="700" align="center"></el-table-column>
      <el-table-column prop="compatibilityRescription" label="配伍药方" width="700" align="center"></el-table-column>
      <el-table-column prop="efficacyEffects" label="功效与作用" width="300" align="center"></el-table-column>
      <el-table-column prop="plantMorphology" label="植物形态" width="700" align="center"></el-table-column>
      <el-table-column prop="harvestingProcessing" label="采收加工" width="190" align="center"></el-table-column>
      <el-table-column prop="meridianTaste" label="性味归经" width="190" align="center"></el-table-column>
      <el-table-column prop="originDistribution" label="产地分布" width="190" align="center"></el-table-column>
      <el-table-column el-table-column fixed="right" label="操作" width="270" align="center">
        <template v-slot="scope">
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItem">添加</el-button>
          <el-button type="warning" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-popconfirm
            title="这是一段内容确定删除吗？"
            icon="el-icon-info"
            icon-color="red"
            @confirm="deleteItem(scope.row)"
            style="margin-left: 5px;white-space: nowrap"
          >
            <el-button :disabled="!deleteButton" slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div style="text-align: right;padding: 10px 20px;" >
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="page.page"
        :page-sizes="[5, 10, 15, 25, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total" />
    </div>
    <!-- 编辑标签弹层 -->
    <div class="add-form">
      <el-dialog title="编辑" :visible.sync="dialogFormVisible4Edit" :modal="false">
        <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" status-icon label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中药名" prop="name">
                <el-input v-model="formData.name"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="别名" prop="alias">
                <el-input v-model="formData.alias"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="药用部位" prop="medicinalPart">
                <el-input v-model="formData.medicinalPart"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="临床应用" prop="clinicalApplication">
                <el-input v-model="formData.clinicalApplication"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="药理研究" prop="pharmacologicalResearch">
                <el-input v-model="formData.pharmacologicalResearch"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用禁忌" prop="contraindications">
                <el-input v-model="formData.contraindications"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="分类" prop="category">
                <el-select v-model="formData.category" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                  <!-- 注意：el-option 设置了 value 属性 -->
                  <el-option v-for="categoryOption in categoryOptions" :key="categoryOption" :label="categoryOption" :value="categoryOption"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="custom-upload-container">
                <div class="upload-title">图片上传</div>
                <el-upload
                  class="avatar-uploader"
                  :action="baseURL + '/image/userImage'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="采收加工" prop="harvestingProcessing">
                <el-input v-model="formData.harvestingProcessing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="功效与作用" prop="efficacyEffects">
                <el-input v-model="formData.efficacyEffects"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="性味归经" prop="meridianTaste">
                <el-input v-model="formData.meridianTaste"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="植物形态" prop="originDistribution">
                <el-input v-model="formData.originDistribution"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="配伍药方" prop="compatibilityRescription">
                <el-input v-model="formData.compatibilityRescription" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="植物形态" prop="chineseMedicineName">
                <el-input v-model="formData.plantMorphology" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div  slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateMedicine">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--添加-->
    <div class="add-form">
      <el-dialog title="添加" :visible.sync="addDialogFormVisible" :modal="false">
        <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" status-icon label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中药名" prop="name">
                <el-input v-model="formData.name"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="别名" prop="alias">
                <el-input v-model="formData.alias"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="药用部位" prop="medicinalPart">
                <el-input v-model="formData.medicinalPart"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="临床应用" prop="clinicalApplication">
                <el-input v-model="formData.clinicalApplication"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="药理研究" prop="pharmacologicalResearch">
                <el-input v-model="formData.pharmacologicalResearch"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用禁忌" prop="contraindications">
                <el-input v-model="formData.contraindications"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="分类" prop="category">
                <el-select v-model="formData.category" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                  <!-- 注意：el-option 设置了 value 属性 -->
                  <el-option v-for="categoryOption in categoryOptions" :key="categoryOption" :label="categoryOption" :value="categoryOption"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="custom-upload-container">
                <div class="upload-title">图片上传</div>
                <el-upload
                  class="avatar-uploader"
                  :action="baseURL+ '/image/userImage'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="采收加工" prop="harvestingProcessing">
                <el-input v-model="formData.harvestingProcessing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="功效与作用" prop="efficacyEffects">
                <el-input v-model="formData.efficacyEffects"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="性味归经" prop="meridianTaste">
                <el-input v-model="formData.meridianTaste"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="植物形态" prop="originDistribution">
                <el-input v-model="formData.originDistribution"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="配伍药方" prop="compatibilityRescription">
                <el-input v-model="formData.compatibilityRescription" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="植物形态" prop="chineseMedicineName">
                <el-input v-model="formData.plantMorphology" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div  slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertMedicineItem">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import zhCn from 'element-ui/lib/locale/lang/zh-CN'
// 封装的接口
import { TcMedicine, TcMedicineEdit, TcMedicineCategory, TcMedicineAdd, TcMedicineDelete, TcMedicineUpdate } from '@/api/medicine'
import request from '@/api/request'

export default {
  data () {
    return {
      locale: zhCn,
      tableData: [],
      searchForm: {
        entrydate: null
      },
      baseURL: '',
      page: {
        total: 7,
        currentPage: 1,
        pageSize: 3,
        queryString: ''
      },
      deleteButton: false,
      imageUrl: '',
      selectedRows: [],
      categoryOptions: [],
      formData: {
        imageUrl: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入中药名', trigger: 'blur' }
        ],
        alias: [
          { required: true, message: '请输入别名', trigger: 'blur' }
        ],
        medicinalPart: [
          { required: true, message: '请输入药用部位', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ]
      },
      formList: {},
      dialogFormVisible4Edit: false,
      addDialogFormVisible: false
    }
  },
  created () {
    this.getData()
    this.getTcMedicineCategory()
    this.baseURL = this.$requestcode.defaults.baseURL
  },
  methods: {
    async getTcMedicineCategory () {
      await TcMedicineCategory().then(resp => {
        const data = resp.data
        // 将对象中的category 属性，组装成新的数组
        this.categoryOptions = data.data.map(item => item.category)
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    async getData () {
      const classData = {
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize,
        queryString: this.page.queryString
      }
      // 发送请求获取分页数据
      await TcMedicine(classData).then(resp => {
        const data = resp.data
        this.page.total = data.total
        this.promisesion()
        this.tableData = data.rows
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    onSubmit () {
      this.getData()
    },
    // 数据回显
    async handleUpdate (row) {
      await TcMedicineEdit(row.id).then(resp => {
        const data = resp.data.data
        this.formData = data
      }).catch(error => {
        this.handleAxiosError(error)
      })
      this.dialogFormVisible4Edit = true
    },
    promisesion () {
      request.get('/req/request', {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + localStorage.getItem('token')
        }
      }).then(resp => {
        // alert(resp.data.flag === true)
        if (resp.data.flag === true) {
          this.deleteButton = true
        } else {
          this.deleteButton = false
        }
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    // 更新
    handleUpdateMedicine () {
      this.$refs.dataEditForm.validate(vale => {
        if (vale) {
          TcMedicineUpdate(this.formData, {
            headers: {
              Authorization: 'Bearer ' + localStorage.getItem('token')
            }
          }).then(resp => {
            const data = resp.data
            if (data.flag === true) {
              this.$message({
                message: data.message,
                type: 'success',
                center: true
              })
              this.imageUrl = ''
              this.dialogFormVisible4Edit = false
            } else {
              this.$message({
                message: data.message,
                type: 'error',
                center: true
              })
            }
            this.getData()
          }).catch(error => {
            this.handleAxiosError(error)
          })
        }
      })
    },
    // 选择
    handleSelectionChange (selection) {
      this.selectedRows = selection
    },
    deleteItem (row) {
      TcMedicineDelete(row.id, {
        headers: {
          Accept: 'application/json',
          Authorization: 'Bearer ' + localStorage.getItem('token')
        }
      }).then(resp => {
        const data = resp.data
        if (data.flag === true) {
          this.$message({
            message: data.message,
            type: 'success',
            center: true
          })
        } else {
          this.$message({
            message: data.message,
            type: 'error',
            center: true
          })
        }
        this.getData()
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    // 批量删除
    async batchDeletion () {
      // 先获取选中的id const ids = this.selectedRows.map(row => row.id)
      if (this.selectedRows.length === 0) {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning',
          center: true
        })
        return
      }

      try {
        await this.$confirm('此操作将永久删除当前选中数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const ids = this.selectedRows.map(row => row.id)
        // alert(ids)
        const resp = await TcMedicineDelete(ids)

        const data = resp.data
        if (data.flag === true) {
          this.$message({
            message: data.message,
            type: 'success',
            center: true
          })
          this.getData()
        } else {
          this.$message({
            message: data.message,
            type: 'error',
            center: true
          })
        }
      } catch (error) {
        // 如果是取消操作，不需要处理
        if (error.message !== 'cancel') {
          console.error('Error during batch deletion:', error)
          // 处理其他错误
        }
      }
    },
    refreshTr () {
      this.page.queryString = ''
      this.getData()
    },
    addItem () {
      this.formData = {}
      this.formList = {}
      this.addDialogFormVisible = true
    },
    async insertMedicineItem () {
      this.$refs.dataEditForm.validate(vale => {
        if (vale) {
          TcMedicineAdd(this.formData, {
            headers: {
              accept: 'application/json',
              Authorization: 'Bearer ' + localStorage.getItem('token')
            }
          }).then(resp => {
            const data = resp.data
            if (data.flag === true) {
              this.$message({
                message: data.message,
                type: 'success',
                center: true
              })
              this.imageUrl = ''
              this.getData()
            } else {
              this.$message({
                message: data.message,
                type: 'error',
                center: true
              })
            }
            this.getData()
          }).catch(error => {
            this.handleAxiosError(error)
          })
          this.addDialogFormVisible = false
        }
      })
    },
    handlePageSizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.page.currentPage = 1 // 重置为第一页
      this.getData()
    },
    handleCurrentPageChange (currentPage) {
      this.page.currentPage = currentPage
      this.getData()
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.formData.imageUrl = res.data
    },
    beforeAvatarUpload (file) {
      const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'] // 允许的文件格式

      const isAllowedFormat = allowedFormats.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isAllowedFormat) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isAllowedFormat && isLt2M
    },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    }
  }
}
</script>

<style>
.avatar-uploader-icon {
  font-size: 25px;
  color: #2667c4;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #bcbebf;
  margin: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.custom-upload-container {
  display: flex;
  align-items: center;
  margin-left: 25px;
}

.upload-title {
  margin-left: 10px;
  white-space: nowrap;
}
</style>
